<template>
  <div class="app-container">
    <el-input v-model="search.keyword" placeholder="keyword " style="width:200px" />
    <el-button type="primary" @click="getWorkOrderList">Search</el-button>
    <el-button type="primary" @click="handleAddWorkOrder">Add</el-button>
    <el-date-picker v-model="search.time_start" type="date" placeholder="Start Date" />
    <el-date-picker v-model="search.time_end" type="date" placeholder="End Date" />
    <el-button type="success" icon="el-icon-refresh" circle @click="getWorkOrderList" />
    <el-input v-model.number="total_row_num" placeholder="Quantity" style="width: 100px" @oninput="value=value.replace(/^\d+$|^\d+[.]?\d+$/,'')" />
    <el-button type="primary" icon="el-icon-download" circle @click="selectPage" />
    <el-popover
      v-model="emailVisible"
      placement="top"
      width="400"
    >
      <el-form ref="emailForm" :model="emailModel" :rules="emailRules" label-width="60px" label-position="left">
        <el-form-item v-for="(email, index) in emailModel.emails" :key="index" label="Email" prop="email">
          <el-row>
            <el-col :span="20">
              <el-input v-model="emailModel.emails[index]" placeholder="Email" />
            </el-col>
            <el-col :span="4" style="padding-left:20px">
              <el-link icon="el-icon-delete" @click="delEmail(index)" />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <el-button type="primary" size="mini" @click="addEmail">add</el-button>
      <div style="text-align: right; margin: 0">
        <el-button size="mini" type="text" @click="emailVisible = false">cancel</el-button>
        <el-button type="primary" size="mini" @click="sendEmail">send</el-button>
      </div>
      <el-button slot="reference" type="primary" icon="el-icon-message" circle />
    </el-popover>

    <el-table :data="workOrderList" style="width: 100%;margin-top:30px;" border :cell-style="cellChangeColor" :empty-text="empty_text">
      <el-table-column align="center" label="ID" width="70">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" label="Tittle" width="200">
        <template slot-scope="scope">{{ scope.row.title }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Work Instruction" min-width="400">
        <template slot-scope="scope">{{ scope.row.wi_names }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Due Date" width="180">
        <template slot-scope="scope">{{ scope.row.due_date }}</template>
      </el-table-column>
      <el-table-column align="center" label="Status">
        <template slot-scope="scope">
          <span :class="scope.row.status === 2?'table-info-row2' : (scope.row.status === 3? 'table-info-row3': '')">
            {{ scope.row.status_name }}
          </span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="slot, prev, pager, next"
      :total="total"
      :current-page="search.page"
      :page-size="pagesize"
      style="margin-top:10px; float:right"
      @current-change="getPageList"
    >
      <span class="el-pagination__total">Total {{ total }}</span>
    </el-pagination>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? 'Edit WorkOrder' : 'New WorkOrder'"
    >
      <el-form :model="workOrder" label-width="160px" label-position="left">
        <el-form-item label="Client & Hotel">
          <el-select v-model="workOrder.hotel_id" placeholder="Please Choose" no-data-text="Can't find record">
            <el-option
              v-for="item in hotelList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Job Title">
          <el-input v-model="workOrder.title" placeholder="Job Title" />
        </el-form-item>
        <el-form-item label="Room & Others">
          <el-input v-model="workOrder.desc" placeholder="Room & Others" />
        </el-form-item>
        <el-form-item label="Work/Job Instruction">
          <el-select v-model="workOrder.wi_ids" multiple collapse-tags placeholder="Please Choose" no-data-text="Can't find record" style="width:100%">
            <el-option
              v-for="item in wiIdList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Priority">
          <el-select v-model="workOrder.priority" placeholder="Please Choose" no-data-text="Can't find record">
            <el-option
              v-for="item in priorityList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Contact Person">
          <el-select v-model="workOrder.hotel_contact_ids" multiple collapse-tags placeholder="Please Choose" no-data-text="Can't find record" style="width:100%">
            <el-option
              v-for="item in hotelContactList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Assign To">
          <el-select v-model="workOrder.staffs" multiple collapse-tags placeholder="Please Choose" no-data-text="Can't find record" style="width:100%">
            <el-option
              v-for="item in userIdList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Add Notes">
          <el-input
            v-model="workOrder.note"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="Add Notes"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="confirmRole">Confirm</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible_per"
      title="Download"
      width="500px"
    >
      <div>
        <el-row style="margin-bottom:20px;margin-top: -10px;padding-left: 20px">
          <el-col v-for="item in total_row_total" :key="item" :span="6" style="margin-bottom:10px">
            <el-link type="primary" @click="downloadWorkOrder(item)">Page {{ item }}</el-link>
          </el-col>
        </el-row>
      </div>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible_per = false">Cancel</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { baseAPI } from '@/utils/request'
import { parseTime } from '@/utils'
import { getWorkOrderList, addWorkOrder, deleteWorkOrder } from '@/api/hotel/detail'
import { getDictionary } from '@/api/user'
import { getToken } from '@/utils/auth' // get token from cookie

const defaultWorkOrder = {
  id: 0,
  hotel_id: '',
  hotel_contact_ids: [],
  title: '',
  desc: '',
  wi_ids: [],
  priority: '',
  staffs: [],
  note: ''
}

export default {
  data() {
    return {
      workOrder: Object.assign({}, defaultWorkOrder),
      total_row_num: 50,
      total_row_total: undefined,
      dialogVisible_per: false,
      emailVisible: false,
      emailModel: {
        emails: ['']
      },
      empty_text: '',
      hotelList: [],
      hotelContactList: [],
      wiIdList: [],
      userIdList: [],
      priorityList: [],
      routes: [],
      workOrderList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      tokenData: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      emailRules: {
        email: [
          { type: 'email', message: 'Please enter the correct email format', trigger: 'blur' }]
      },
      search: {
        keyword: '',
        time_start: '',
        time_end: '',
        hotel_id: '',
        request_type: '',
        page: 1
      },
      total: 10,
      pagesize: 1
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  watch: {
    emailVisible(newValue, oldValue) {
      if (this.$refs['emailForm']) this.$refs['emailForm'].clearValidate()
      if (!newValue) {
        this.emailModel.emails = ['']
      }
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getWorkOrderList()
    this.conToken()
  },
  methods: {
    addEmail() {
      this.emailModel.emails.push('')
    },
    delEmail(val) {
      this.emailModel.emails.splice(val, 1)
    },
    async getRoutes() {
      const res = await baseAPI.get('user/role/routes')
      this.serviceRoutes = res
      this.routes = res
    },
    async conToken() {
      this.tokenData = getToken()
    },
    cellChangeColor({ row, column, rowIndex, columnIndex }) {
      if (row.status === 2 && columnIndex === 4) { return { backgroundColor: '#9267be', color: 'white' } }
      if (row.status === 3 && columnIndex === 4) { return { backgroundColor: '#6ed3d0' } }
      if (row.overdue && columnIndex === 3) { return { backgroundColor: '#f74969', color: 'white' } }
      return ''
    },
    async getSelectList() {
      // 宾馆
      await getDictionary({ dict_type: 'hotel' }).then(result => {
        this.hotelList = result
      })
      // 宾馆联系人
      await getDictionary({ dict_type: 'hotel_contact', hotel_id: this.search.hotel_id }).then(result => {
        this.hotelContactList = result
      })
      // 流程
      await getDictionary({ dict_type: 'wi' }).then(result => {
        this.wiIdList = result
      })
      // 订单 - 优先级
      await getDictionary({ dict_type: 'priority' }).then(result => {
        this.priorityList = result
        this.workOrder.priority = 2
      })
      // 员工
      await getDictionary({ dict_type: 'staff' }).then(result => {
        this.userIdList = result
      })
    },
    async getWorkOrderList() {
      if (this.search.time_start) {
        this.search.time_start = parseTime(this.search.time_start, '{y}-{m}-{d}')
      }
      if (this.search.time_end) {
        this.search.time_end = parseTime(this.search.time_end, '{y}-{m}-{d}')
      }
      this.empty_text = 'Loading ......'
      await getWorkOrderList(this.search).then(response => {
        this.workOrderList = response.data
        this.total = response.total
        this.search.page = parseInt(response.current_page)
        this.pagesize = response.per_page
        this.empty_text = 'Can\'t find record in table'
      }).catch(() => {
        this.rolesList = []
        this.empty_text = 'Can\'t find record in table'
      })
    },
    async getPageList(value) {
      this.search.page = value
      if (this.search.time_start) {
        this.search.time_start = parseTime(this.search.time_start, '{y}-{m}-{d}')
      }
      if (this.search.time_end) {
        this.search.time_end = parseTime(this.search.time_end, '{y}-{m}-{d}')
      }
      this.empty_text = 'Loading ......'
      await getWorkOrderList(this.search).then(res => {
        this.workOrderList = res.data
        this.total = res.total
        this.search.page = res.current_page
        this.pagesize = res.per_page
        this.empty_text = 'Can\'t find record in table'
      }).catch(() => {
        this.rolesList = []
        this.empty_text = 'Can\'t find record in table'
      })
    },
    handleAddWorkOrder() {
      this.workOrder = Object.assign({}, defaultWorkOrder)
      this.getSelectList()
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.$router.push({
        path: 'hotelDetailIndex',
        query: { id: scope.row.id, name: scope.row.hotel_name, address: scope.row.address }
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('Confirm to remove the role?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
        .then(async() => {
          await deleteWorkOrder({ id: row.id })
          // this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    async confirmRole() {
      // this.workOrder.start_time = parseTime(this.workOrder.start_time, '{y}-{m}-{d}')
      this.workOrder.notes = []
      this.workOrder.notes[0] = this.workOrder.note
      await addWorkOrder(this.workOrder).then(async() => {
        0
        const { title, desc } = this.workOrder
        this.dialogVisible = false
        this.$notify({
          title: 'Success',
          dangerouslyUseHTMLString: true,
          message: `
              <div>title: ${title}</div>
              <div>Description: ${desc}</div>
            `,
          type: 'success'
        })

        // 更新列表
        await this.getWorkOrderList()
      })
    },
    async selectPage() {
      if (!this.total_row_num || this.total_row_num <= 0) {
        this.$message({
          type: 'warning',
          message: 'Please enter the quantity per page!'
        })
        return
      } else {
        const per_search = Object.assign({}, this.search)
        per_search.request_type = 'download_query'

        await getWorkOrderList(per_search).then(async response => {
          if (response.total > 0) {
            this.total_row_total = Math.ceil(response.total / this.total_row_num)
            this.dialogVisible_per = true
          } else {
            this.$message({
              type: 'warning',
              message: 'Can\'t find record to download!'
            })
          }
        })
      }
    },
    async downloadWorkOrder(value) {
      this.downloadSearch = Object.assign({}, this.search)
      this.downloadSearch.download = 1
      if (this.downloadSearch.time_start) {
        this.downloadSearch.time_start = parseTime(this.downloadSearch.time_start, '{y}-{m}-{d}')
      }
      if (this.downloadSearch.time_end) {
        this.downloadSearch.time_end = parseTime(this.downloadSearch.time_end, '{y}-{m}-{d}')
      }
      const url = 'user/order/index?keyword=' + this.downloadSearch.keyword + '&page=' + value + '&per_page=' + this.total_row_num + '&hotel_id=' + this.downloadSearch.hotel_id +
      '&time_start=' + this.downloadSearch.time_start + '&time_end=' + this.downloadSearch.time_end + '&request_type=download&token=' + this.tokenData
      console.log(url)
      window.open('http://work.dcloud.yunku.live/api/' + url)
    },
    async sendEmail() {
      this.$refs.emailForm.validate(async valid => {
        if (valid) {
          this.downloadSearch = Object.assign({}, this.search)
          this.downloadSearch.download = 1
          if (this.downloadSearch.time_start) {
            this.downloadSearch.time_start = parseTime(this.downloadSearch.time_start, '{y}-{m}-{d}')
          }
          if (this.downloadSearch.time_end) {
            this.downloadSearch.time_end = parseTime(this.downloadSearch.time_end, '{y}-{m}-{d}')
          }
          const requestEmail = this.emailModel.emails.join(',')
          const url = 'user/order/index?keyword=' + this.downloadSearch.keyword + '&page=' + this.downloadSearch.page + '&hotel_id=' + this.downloadSearch.hotel_id +
          '&time_start=' + this.downloadSearch.time_start + '&time_end=' + this.downloadSearch.time_end + '&request_type=send_email&emails=' + requestEmail
          await baseAPI.get(url)
          this.emailVisible = false
          this.$message({
            type: 'success',
            message: 'Email sent successfully!'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .table-info-row2 td {
    background-color: #C0C4CC;
  }
  .table-info-row3 td {
    background-color: #909399;
  }
}
</style>
